export function random(start: number, end: number) {
    return Math.floor(Math.random() * (end - start + 1)) + start
}

export function shuffle<T>(array: T[]): T[] {
    const shuffled = [...array]
    for (let i = shuffled.length - 1; i > 0; i--) {
        const j = random(0, i)
        ;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
    }
    return shuffled
}

export function groupBy<T>(arr: T[], key: (item: T) => string) {
    return arr.reduce(
        (r, a) => {
            const keyValue = key(a)
            r[keyValue] = [...(r[keyValue] || []), a]
            return r
        },
        {} as Record<string, T[]>,
    )
}

export function toggleArrayItem<T>(arr: T[], item: T) {
    const index = arr.indexOf(item)
    if (index > -1) {
        arr.splice(index, 1)
    } else {
        arr.push(item)
    }
    return arr
}
